from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers

from goods.models import Brand, SKUImage


# class BrandSerializer(serializers.Serializer):
#     id = serializers.IntegerField(label='id', read_only=True)
#     name = serializers.CharField(max_length=20, label='名称')
#     logo = serializers.CharField(label='图片地址')
#     first_letter = serializers.CharField(label='品牌首字母', max_length=1)

class BrandSerializer(serializers.ModelSerializer):
    """
        品牌序列化器
    """

    class Meta:
        model = Brand
        fields = '__all__'

    def create(self, validated_data):
        # 1.建立fasdDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 2.获取图片数据 在序列化器中获取request对象
        request = self.context['request']
        image_file = request.data.get('logo')
        # 3.上传图片
        res = client.upload_by_buffer(image_file.read())
        # 4.判断结果
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 5.上传成功将返回的文件路径保存到图片表中
        image_url = res['Remote file_id']
        validated_data['logo'] = image_url
        img = Brand.objects.create(**validated_data)
        return img

    def update(self, instance, validated_data):
        # 1.建立fasdDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 2.获取图片数据 在序列化器中获取request对象
        request = self.context['request']
        image_file = request.data.get('logo')
        # 3.上传图片
        res = client.upload_by_buffer(image_file.read())
        # 4.判断返回结果
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 5.上传成功将返回的文件路径更新到图片表中
        image_url = res['Remote file_id']
        validated_data['logo'] = image_url

        Brand.objects.filter(id=instance.id).update(**validated_data)
        img = Brand.objects.get(id=instance.id)

        # 6.返回保存后的图片对象数据
        return img
